//
//  HSYUserCenter.m
//  HSY
//
//  Created by 陈浩 on 2017/3/31.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYUserCenter.h"
#import "HSYLogoutRequest.h"
#import "HSYGetBalanceRequest.h"
#import "BQActivityView.h"

static HSYUserCenter *user = nil;

@implementation HSYUserCenter

@synthesize accessToken = _accessToken;
@synthesize encryptKey = _encryptKey;


+(instancetype) instatce{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        user = [[self alloc] init];
    });
    return user;
}

+(id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        user = [super allocWithZone:zone];
    });
    
    return user;
}

#if !__has_feature(objc_arc)

-(id)mutableCopyWithZone:(NSZone *)zone{
    return user;
}

-(id)copyWithZone:(NSZone *)zone{
    return user;
}

#endif

#pragma mark - getters & setters -

-(NSString *)accessToken{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
}

-(void)setAccessToken:(NSString *)accessToken{
    if (_accessToken != accessToken) {
        _accessToken = accessToken;
        [[NSUserDefaults standardUserDefaults] setObject:_accessToken forKey:@"accessToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

-(NSString *)encryptKey{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"encryptKey"];
}

-(void)setEncryptKey:(NSString *)encryptKey{
    if (_encryptKey != encryptKey) {
        _encryptKey = encryptKey;
        [[NSUserDefaults standardUserDefaults] setObject:_encryptKey forKey:@"encryptKey"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark - Public methods -
- (void)restoreUserModel{
    [HSYUserModel restoreMyself];
    [HSYShopInfo restoreShopInfo];
    [HSYCardInfo restoreCardInfo];
    
    self.appAuUser = [HSYUserModel sharedCurrentUser];
    self.appBizShop = [HSYShopInfo sharedShopInfo];
    self.appBizCard = [HSYCardInfo sharedCardInfo];
    
    self.available = [[NSUserDefaults standardUserDefaults] objectForKey:@"User_available"];
    self.dueSettleAmount = [[NSUserDefaults standardUserDefaults] objectForKey:@"User_dueSettleAmount"];
    self.frozenAmount = [[NSUserDefaults standardUserDefaults] objectForKey:@"User_frozenAmount"];
    self.totalAmount = [[NSUserDefaults standardUserDefaults] objectForKey:@"User_totalAmount"];
    self.accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    self.encryptKey = [[NSUserDefaults standardUserDefaults] objectForKey:@"encryptKey"];
    
}
- (void)saveUserModelToDocuments{
    [HSYUserModel saveMyselfToDocuments];
    [HSYShopInfo saveShopInfoToDocuments];
    [HSYCardInfo saveCardInfoToDocuments];
    
    [[NSUserDefaults standardUserDefaults] setObject:self.available forKey:@"User_available"];
    [[NSUserDefaults standardUserDefaults] setObject:self.dueSettleAmount forKey:@"User_dueSettleAmount"];
    [[NSUserDefaults standardUserDefaults] setObject:self.frozenAmount forKey:@"User_frozenAmount"];
    [[NSUserDefaults standardUserDefaults] setObject:self.totalAmount forKey:@"User_totalAmount"];
    [[NSUserDefaults standardUserDefaults] synchronize];;
    
}
- (void)removeSaveUserModelFromDocuments{
    [HSYUserModel removeSaveSelf];
    [HSYShopInfo removeSaveShopInfo];
    [HSYCardInfo removeSaveCardInfo];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"User_available"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"User_dueSettleAmount"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"User_frozenAmount"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"User_totalAmount"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"accessToken"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"encryptKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self restoreUserModel];
}


- (void)logoutWithCompletionBlock:(void(^)(BOOL result,NSString *errorStr))completionBlock{
    
    HSYLogoutRequest *task = [[HSYLogoutRequest alloc] init];
    task.accessToken = self.accessToken;
    
    __weak typeof(self)weakSelf = self;
    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            [weakSelf removeSaveUserModelFromDocuments]; //本地化用户信息
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRefreshBalance object:response.encryptDataResult]; //发送通知，更新余额信息
            
            if (completionBlock) {
                completionBlock(YES,nil);
            }
        }else{
            completionBlock(NO,response.resultMessage); //失败，返回错误信息
        }
    } failure:^(NSError *error) {
        [BQActivityView hideActiviTy];
        completionBlock(NO,@"请求超时");

    }];
}

-(void)getBalanceSuccess:(void(^) (NSDictionary *info))success failure:(void(^)(NSString *errorInfo))failure
{
    
    HSYGetBalanceRequest *task = [[HSYGetBalanceRequest alloc] init];
    task.uid = [HSYUserCenter instatce].appAuUser.uid;
    
    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            HSYUserCenter *userCenter = [HSYUserCenter mj_objectWithKeyValues:response.encryptDataResult];
            [userCenter saveUserModelToDocuments]; //保存用户信息
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRefreshBalance object:response.encryptDataResult];
            
            if (success) {
                success(response.encryptDataResult);
            }
        }else{
            if (failure) {
                failure(response.resultMessage);
            }
        }
    } failure:^(NSError *error) {
        if (error.code != NSURLErrorCancelled) {
            if (failure) {
                failure(@"请求超时");
            }
        }
    }];
}

-(void)checkAppUpDate{
    
}


@end
